<template>
  <div class="home">
    <button @click="handleSSOLogin" class="nav-button">登陆</button>
    <div v-if="tokenRes">
       token信息： {{tokenRes}}
    </div>
    <div v-if="userInfo">
       用户信息： {{ JSON.stringify(userInfo) }}
    </div>
  </div>
</template>

<script setup>
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { generateCodeChallenge, generateCodeVerifier } from "@/utils/pkce";
const tokenRes = computed(() => { 
    localStorage.getItem('tokenResponse')
})
const router = useRouter()
const redirectUri = ref(
    window.location.origin + router.resolve({ path: "/callback" }).href
);
let loginWindow = null;

const userInfo = ref()

const codeVerifier = ref("");
const clientId = ref(import.meta.env.VITE_OPENIDDICT_CLIENT_ID);
const handleSSOLogin = async() => {
  codeVerifier.value = await generateCodeVerifier();
    const codeChallenge = await generateCodeChallenge(codeVerifier.value);
    // 生成随机state值（防CSRF）
    const state = Math.random().toString(36).substring(2);
    localStorage.setItem('state', state);
    localStorage.setItem('code_verifier', codeVerifier.value);
    const authUrl =
        `${import.meta.env.VITE_API_BASE_AUTH_URL}/connect/authorize?` +
        `response_type=code` +
        `&client_id=${clientId.value}` +
        `&redirect_uri=${encodeURIComponent(redirectUri.value)}` +
        `&scope=openid profile offline_access` +
        `&state=${state}` +
        `&code_challenge=${codeChallenge}` +
        // `&code_verifier=${codeVerifier.value}` +
        `&code_challenge_method=S256`;
    // window.location.href = authUrl;
    loginWindow = window.open(
        authUrl,
        '_blank',
        'width=900,height=600,menubar=no,toolbar=no,location=no,status=no,resizable=yes,scrollbars=yes'
    );
}

window.addEventListener('message', async (event) => {
  if (event.data && event.data.type === 'auth-success') {
    localStorage.setItem('userInfo', event.data.userInfo);
    userInfo.value = event.data.userInfo;
  }
})
</script>

<style scoped>
.home {
  text-align: center;
  padding: 2rem;
}

.nav-link {
  display: inline-block;
  margin-top: 1rem;
  padding: 0.5rem 1rem;
  color: #42b883;
  text-decoration: none;
  border: 1px solid #42b883;
  border-radius: 4px;
  transition: all 0.3s;
}

.nav-link:hover {
  background-color: #42b883;
  color: white;
}
</style>